package service

import (
	"context"
	"nearby/biz/common"
	domainService "nearby/biz/domain/service"
	"nearby/biz/model"
)

type WxLoginService struct {
}

func (ss *WxLoginService) Execute(ctx context.Context, req *model.WxLoginRequest) (resp *model.WxLoginResponse, err error) {
	var userService domainService.UserService
	// 1. 拿req.WxCode换wx_session
	wxSession, err := userService.GetWxSession(ctx, req.WxCode)
	if err != nil {
		return nil, common.NewBizErr(common.WxLoginFailErrCode, "getWxOpenID fail", err)
	}
	if wxSession == nil {
		return nil, common.NewBizErr(common.WxLoginFailErrCode, "getWxOpenID fail, the wxSession is nil", err)
	}
	// 2. 根据wx_session提供的open_id, 找到这个用户
	userEntity, err := userService.GetUserEntityByOpenID(ctx, wxSession.OpenID)
	if err != nil {
		return nil, common.NewBizErr(common.WxLoginFailErrCode, "userService.GetUserEntityByOpenID fail", err)
	}
	if userEntity == nil {
		return nil, common.NewBizErr(common.HasNotRegisteredErrCode, "user has not registered", err)
	}
	// 3. 生成token返回给前端
	token, err := userEntity.GenerateToken()
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "userEntity.GenerateToken fail", err)
	}
	// todo ctx.SetCookie
	resp = &model.WxLoginResponse{
		Meta:           common.MetaOk,
		Token:          token.Token,
		TokenExpiredAt: token.TokenExpiredAt,
	}
	return resp, nil
}
